package nio;

import org.junit.jupiter.api.Test;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: 康大
 * \* Date: 2019/4/29
 * \* Time: 13:37
 * \* To change this template use File | Settings | File Templates.
 * \* Description:
 * \
 * 通道主要实现类
 * java.nio.channels.Channel接口：
 *      FileChannel
 *      SocketChannel
 *      ServerSocketChannel
 *      DatagramChannel
 * 1.Java针对支持通道的类提供了getChannel()方法
 * 2.JDK7 中的NIO.2针对各个通道提供了静态方法open()
 * 3.JDK7 中的NIO.2的Files 工具类的newByteChannel()
 */
public class Channel {
    @Test
    public void test1() {
        try(FileInputStream fis = new FileInputStream("1.jpg");
            FileOutputStream fos = new FileOutputStream("2.jpg");
            FileChannel inChannel = fis.getChannel();
            FileChannel outChannel = fos.getChannel();) {
            ByteBuffer buf = ByteBuffer.allocate(1024);
            while (inChannel.read(buf) != -1) {
                buf.flip();
                outChannel.write(buf);
                buf.clear();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
